package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Description: 菜品管理
 * @Author: Zonghe Wang
 * @Date: 2025/1/20 12:14
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetMealDishMapper setMealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        // 菜品表添加数据 1跳
        dishMapper.insert(dish);

        Long dishId = dish.getId();

        // 口味表插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        // 判断当前菜品是否能够删除(是否存在起售中、当前菜品是否被套餐关联)
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                // 起售中不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        List<Long> list = setMealDishMapper.getByDishIds(ids);
        if (list != null && !list.isEmpty()) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 删除菜品表中菜品数据
        dishMapper.deleteByIds(ids);
        // 删除菜品关联的口味数据
        dishFlavorMapper.deleteByDishIds(ids);

    }

    @Override
    @Transactional
    public DishVO getByID(Long id) {
        Dish dish = dishMapper.getById(id);
        DishVO dishVo = new DishVO();
        BeanUtils.copyProperties(dish, dishVo);

        List<DishFlavor> flavor = dishFlavorMapper.getByDishId(id);
        dishVo.setFlavors(flavor);
        return dishVo;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //修改dish表
        dishMapper.updateById(dish);

        // 修改口味表
        // 先删除
        dishFlavorMapper.deleteByDishIds(Collections.singletonList(dishDTO.getId()));
        // 后新增
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(flavor -> {
                flavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public List<Dish> list(Long categoryId) {

        // 构造redis中的Key，规则：dish_分类id
        String key = "dish_" + categoryId;
        // 查询redis中是否存在缓存数据
        ValueOperations ops = redisTemplate.opsForValue();
        List<Dish> list = (List<Dish>) ops.get(key);
        // 存在，直接返回，无需查询数据库
        if (list != null && !list.isEmpty()) {
            return list;
        }
        // 不存在，查询数据库，并存入redis
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        List<Dish> dishes = dishMapper.list(dish);
        ops.set(key, dishes);
        return dishes;
    }

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {

        // 配置Key
        String Key = "dish_flavor_" + dish.getCategoryId();
        // 查询redis中
        ValueOperations ops = redisTemplate.opsForValue();
        List<DishVO> list = (List<DishVO>) ops.get(Key);
        // redis中存在，直接返回
        if (list != null && !list.isEmpty()) {
            return list;
        }

        // 不存在，查询数据库，并存入redis
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        ops.set(Key, dishVOList);
        return dishVOList;
    }

    @Override
    public void updateStatusById(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.updateById(dish);
    }
}
